package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TDictMapper;
import com.bwie.mapper.TProdImageMapper;
import com.bwie.pojo.TDict;
import com.bwie.pojo.TLog;
import com.bwie.pojo.TProd;
import com.bwie.pojo.TProdImage;
import com.bwie.service.TProdService;
import com.bwie.mapper.TProdMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.ptg.TblPtg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

/**
* @author Yoo19
* @description 针对表【t_prod】的数据库操作Service实现
* @createDate 2025-04-24 13:44:23
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class TProdServiceImpl extends ServiceImpl<TProdMapper, TProd>
    implements TProdService{

    @Autowired
    TProdMapper tProdMapper;
    @Autowired
    HttpServletRequest request;
    @Autowired
    TDictMapper tDictMapper;
    @Autowired
    TProdImageMapper tProdImageMapper;
    @Autowired
    KafkaTemplate kafkaTemplate;


    @Override
    public R getProdList(PageInfoVo pageInfoVo) {

        Page<TProd> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        Page<TProd> tProdPage = tProdMapper.getProdList(page,pageInfoVo.getKeyWord());

        //获取图片列表

        for (TProd record : tProdPage.getRecords()) {
            List<TProdImage> list = tProdImageMapper.selectList(new LambdaQueryWrapper<TProdImage>().eq(TProdImage::getProdId, record.getProdId()));
            record.setProdImageList(list);
        }

        for (TProd record : tProdPage.getRecords()) {
            record.setBuyNum(1);
        }

        return R.OK(tProdPage);
    }

    @Override
    public R addProd(TProd tProd) {

        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(500,"请先登陆");
        }

        Claims claims = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = claims.get("userId", Integer.class);

        TProd one = tProdMapper.selectOne(new LambdaQueryWrapper<TProd>().eq(TProd::getProdName, tProd.getProdName()));
        if(one!=null){
            return R.ERROR(500,"该商品已存在");
        }

        tProd.setCreateTime(new Date());
        tProd.setProdStatus(0);
        tProd.setUserId(userId);

        tProdMapper.insert(tProd);

        //添加商品图片
        if(tProd.getProdImageList() !=null && tProd.getProdImageList().size() > 0){
            for (TProdImage tProdImage : tProd.getProdImageList()) {
                tProdImage.setProdId(tProd.getProdId());
                tProdImageMapper.insert(tProdImage);
            }
        }
        return R.OK();
    }

    @Override
    public R getDictList(Integer typeId) {
        List<TDict> tDicts = tDictMapper.selectList(new LambdaQueryWrapper<TDict>().eq(TDict::getDictType, typeId));
        return R.OK(tDicts);
    }

    @Override
    public R deleteProd(Integer prodId) {
        //先删除图片
        tProdImageMapper.delete(new LambdaQueryWrapper<TProdImage>().eq(TProdImage::getProdId,prodId));
        //删除商品
        tProdMapper.deleteById(prodId);
        return R.OK();
    }

    @Override
    public R updateProd(TProd tProd) {
        //判断商品是否存在
        TProd one = tProdMapper.selectOne(new LambdaQueryWrapper<TProd>().eq(TProd::getProdName, tProd.getProdName()));
        if(one!=null){
            return R.ERROR(500,"用户已存在");
        }

        tProdMapper.updateById(tProd);

        tProdImageMapper.delete(new LambdaQueryWrapper<TProdImage>().eq(TProdImage::getProdId,tProd.getProdId()));

        if(tProd.getProdImageList()!=null && tProd.getProdImageList().size() > 0){
            for (TProdImage tProdImage : tProd.getProdImageList()) {
                tProdImage.setProdId(tProd.getProdId());
                tProdImageMapper.insert(tProdImage);
            }
        }

        return R.OK();
    }

    @Override
    public R sendMessage(String msg) {
        System.out.println("发送消息:"+msg);
        kafkaTemplate.send("topic-test",msg);
        return R.OK();
    }

    @Override
    public R changeProdStatus(TProd tProd) {

        TLog tLog = new TLog();
        tLog.setCreateTime(new Date());
        tLog.setLogName("商品审核");
        tLog.setIp(request.getRemoteAddr());
        tLog.setLogType(6);
        //解析token 获取用户信息
        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(500,"请先登陆");
        }
        Claims claims = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = claims.get("userId", Integer.class);
        String nickName = claims.get("nickName", String.class);
        tLog.setOptId(userId);
        tLog.setOptName(nickName);

        String message="";

        TProd prod = tProdMapper.selectById(tProd.getProdId());
        if(prod ==null){
            message="商品不存在";
            return R.ERROR(404,"商品不存在");
        }

        //审核商品
        if(tProd.getProdStatus() == 1){
            prod.setProdStatus(tProd.getProdStatus());
            tProdMapper.updateById(tProd);
            message = "提交审核:" + tProd.getProdName();
        }
        //上线(审核通过发送短信)
        if(tProd.getProdStatus() == 2){
            prod.setProdStatus(tProd.getProdStatus());
            tProdMapper.updateById(tProd);

            //异步发送短信
            String msg = JSON.toJSONString(prod);
            kafkaTemplate.send("topic-prod",msg);
            System.out.println("发送短信:"+msg);

            message = "审核通过:" + tProd.getProdName();
        }
        //驳回(发送邮件)
        if(tProd.getProdStatus() == 3){

          if(StringUtils.isEmpty(tProd.getReason())){
              return R.ERROR(500,"驳回必须填写审核理由");
          }
            prod.setProdStatus(tProd.getProdStatus());
            tProdMapper.updateById(tProd);

            //异步发送邮件
            String msg = JSON.toJSONString(prod);
            kafkaTemplate.send("topic-prod",msg);
            System.out.println("发送邮件:"+msg);

            message = "审核驳回:" + tProd.getProdName();
        }
        //下线
        if(tProd.getProdStatus() == 4){
            prod.setProdStatus(tProd.getProdStatus());
            tProdMapper.updateById(tProd);

            message = "商品下线:" + tProd.getProdName();
        }


//        异步记录日志
        tLog.setLogContent(message);
        kafkaTemplate.send("topic-log",JSON.toJSONString(tLog));

        return R.OK();
    }

    @KafkaListener(topics = "topic-test")
    public void  Recvtestmsg(String msg, Acknowledgment acknowledgment){
        System.out.println("接收消息"+msg);
        acknowledgment.acknowledge();
    }
}




